/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.tewi.annotations.processors;

import pl.tewi.contexts.ApplicationServerContext;
import pl.tewi.annotations.ApplicationServer;
import pl.tewi.annotations.Security;
import pl.tewi.exceptions.AnnotationProcessingException;
import pl.tewi.exceptions.GeneralFrameworkException;
import pl.tewi.exceptions.SecurityAnnotationException;

/**
 * Procesor przetwarzający adnotację {@link Security} na potrzeby 
 * {@link ApplicationServerAnnotationProcessor}
 * @author Marcin Kwapisz
 */
class SecurityAnnotationProcessor implements AnnotationProcessor {

    /**
     * Metoda przetwarza adnotację {@link Security}, która jest parametrem adnotacji
     * {@link ApplicationServer}
     * @param klass
     * @param context
     * @return
     * @throws AnnotationProcessingException
     * @throws GeneralFrameworkException 
     */
    public ApplicationServerContext processAnnotations(final Class<?> klass, final ApplicationServerContext context) throws AnnotationProcessingException, GeneralFrameworkException {
        ApplicationServer applicationServer = klass.getAnnotation(ApplicationServer.class);
        Security security = applicationServer.security();
        if (security != null) {
            if (!(security.securityRealmName() == null) && !security.securityRealmName().isEmpty()) {
                context.setSecurityRealmName(security.securityRealmName());
            } else {
                throw new SecurityAnnotationException(SecurityAnnotationException.EMPTY_REALM_NAME);
            }
            String[] users = security.roles();
            if (users == null || users.length == 0) {
                throw new SecurityAnnotationException(SecurityAnnotationException.NO_ROLES);
            }
            for (int i = 0; i < users.length; i++) {
                context.addUser(users[i]);
            }
        } else {
            throw new SecurityAnnotationException(SecurityAnnotationException.NO_SECURITY_ANNOTATION);
        }
        return context;
    }
}
